package com.xrit.sunnyday.controller;

import com.xrit.sunnyday.constant.RedisMessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.utils.SMSUtils;
import com.xrit.sunnyday.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
   @Autowired
   private JedisPool jedisPool;

    /**
     * 发送手机验证码
     */
    @PostMapping("/send4Order")
    public Result send4Order(String telephone){
        //1.获取redis客户端
        Jedis jedis = jedisPool.getResource();
        //2.根据前端手机号码,定义一个key
        String key = RedisMessageConstant.SENDTYPE_ORDER +"_"+ telephone;
        //3.根据key获取redis中的值(验证码)
        String codeInRedis = jedis.get(key);
        //4.判断验证码存不存在于redis
        if (null==codeInRedis){
            //5.不存在，发送短信验证码
            //5.1生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //
            try {
                String[] params = new String[]{code+""};
                //5.2调用腾讯云的短信发送
                SMSUtils.sendSingleMessageForCode(telephone,params);
                //5.3保存到redis备份
                jedis.setex(key,6*60,code+"");
                return new Result(true,"短信发送成功!");
            }catch (Exception e){
                return new Result(false,"短信发送失败！");
            }
        }
        //6.存在
        return new Result(false,"短信验证码已经发送了!!!");
    }

    /**
     * 发送登陆手机验证码
     */
    @PostMapping("/send4Login")
    public Result send4Login(String telephone) {
        //1.获取redis客户端
        Jedis jedis = jedisPool.getResource();
        //2.根据前端手机号码,定义一个key
        String key = RedisMessageConstant.SENDTYPE_LOGIN +"_"+ telephone;
        //3.根据key获取redis中的值(验证码)
        String codeInRedis = jedis.get(key);
        //4.判断验证码存不存在于redis
        if (null==codeInRedis){
            //5.不存在，发送短信验证码
            //5.1生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //
            try {
                String[] params = new String[]{code+""};
                //5.2调用腾讯云的短信发送
                SMSUtils.sendSingleMessageForCode(telephone,params);
                //5.3保存到redis备份
                jedis.setex(key,6*60,code+"");
                return new Result(true,"短信发送成功!");
            }catch (Exception e){
                return new Result(false,"短信发送失败！");
            }
        }
        //6.存在
        return new Result(false,"登录短信验证码已经发送了!!!");
    }
}
